/**
 * @author: yyq
 * @date: 2025年3月14日 17:58:17
 * @description: 
 */
package com.sheepone.monitor.core;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.sheepone.monitor.codec.SheeponeCodec;
import com.sheepone.monitor.util.ChannelHandlerSorter;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author: yyq
 * @date: 2025年3月14日 17:58:17
 * @description:
 */
public abstract class AbstractSheeponeChannelInitializer extends ChannelInitializer<NioSocketChannel> {

    private Map<ChannelHandler, EventLoopGroup> handlers = new HashMap<>();

    protected void addHandler(EventLoopGroup group, ChannelHandler handler) {
        if (handler != null && !(handler instanceof SheeponeCodec)) {
            handlers.put(handler, group);
        }
    }

    protected void addHandler(ChannelHandler handler) {
        addHandler(null, handler);
    }

    protected abstract void beforeInit();

    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        beforeInit();
        ChannelHandlerSorter.sort(handlers.keySet());
        ChannelPipeline pipeline = ch.pipeline();
        // Sheepone协议编解码器
        pipeline.addLast(new SheeponeCodec());
        for (Entry<ChannelHandler, EventLoopGroup> entry : handlers.entrySet()) {
            if (entry.getValue() != null) {
                pipeline.addLast(entry.getValue(), entry.getKey());
            } else {
                pipeline.addLast(entry.getKey());
            }
        }
    }

}
